package org.ilovecode {
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	/**
	 * ...
	 * @author Vjekoslav Ratkajec
	 */
	public class Utilities {
		
		public function Utilities() {
			
		}
		
		public static function loadURL(url:String, func:Function):void {
			var req:URLRequest = new URLRequest(url);
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, func);
			loader.addEventListener(IOErrorEvent.IO_ERROR, loader_IOError);
			try {
				loader.load(req);
			} catch (e:Error) {
				throw e;
			}
		}
		
		public static function loadContent(url:String, func:Function):void {
			var req:URLRequest = new URLRequest(url);
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, func);
			loader.addEventListener(IOErrorEvent.IO_ERROR, loader_IOError);
			try {
				loader.load(req);
			} catch (e:Error) {
				throw e;
			}
		}
		
		private static function loader_IOError(event:IOErrorEvent):void {
			trace("Unable to load from supplied URL");
		}
		
		public static function internationalFormat(number:Number):String {
			return String(number).replace(".", ",").replace(String(number).indexOf(".") > -1 ?/(?<=\d)(?=(\d\d\d)+(?!\d)(?:\,\d*))/g : /(?<=\d)(?=(\d\d\d)+(?!\d))/g, ".").replace(/\.{2,}/g, ".");
		}
		
		public static function americanFormat(number:Number):String {
			return String(number).replace(String(number).indexOf(".") > -1 ? /(?<=\d)(?=(\d\d\d)+(?!\d)(?:\.\d*))/g : /(?<=\d)(?=(\d\d\d)+(?!\d))/g, ",").replace(/,{2,}/g, ",");
		}
		
		public static function getMoney(value:Number, decimal:uint = 0):String {
			var S:String = value.toFixed(decimal);
			var a:Array = S.split(".");
			var result:String = "";
			var target:String = a[0];
			var digits:Array = new Array();
			while (Number(target) > 999) {
				var current:String = target.substr(target.length - 3 , 3);
				digits.unshift(current);
				current = target.substr(0 , target.length - 3);
				target = current;
			}
			result += target;
			if (digits.length > 0) {
				result = result + "." + digits.join(",");
			}
			result += "," + a[1];
			return result;
		}
		
	}

}